<template>
    <div class="login-container">
        <div class="top">
            <van-image class="logo" src="/src/assets/ico.png" />
        </div>
        <van-form @submit="onSubmit">
            <van-field v-model="username" name="username" label="用户名" placeholder="请输入用户名"
                :rules="[{ required: true, message: '请填写用户名' }]" />
            <van-field v-model="password" type="password" name="password" label="密码" placeholder="请输入密码"
                :rules="[{ required: true, message: '请填写密码' }]" />
        </van-form>
        <van-button round block type="primary" native-type="submit" @click="onSubmit">
            登录
        </van-button>
        <div class="bottom">
            <div class="register">还没有账号？<span class="protocol" @click="goRegister">点击注册</span></div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';

const router = useRouter();
const username = ref('');
const password = ref('');

const onSubmit = async () => {
    // 创建请求头
    try {
        const myHeaders = new Headers();
        myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
        myHeaders.append("Content-Type", "application/json");
        myHeaders.append("Accept", "*/*");
        myHeaders.append("Host", "127.0.0.1:9999");
        myHeaders.append("Connection", "keep-alive");

        // 构造请求体（添加 password 字段）
        const raw = JSON.stringify({
            "email": username.value,
        });

        const requestOptions = {
            method: 'POST',
            headers: myHeaders,
            body: raw,
            redirect: 'follow'
        };
        // 调用登录接口（假设实际登录接口是/v2/user/login，根据你的后端调整）
        const response = await fetch("http://127.0.0.1:9999/v2/user/getUserInfoByEmail", requestOptions);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = await response.json();

        // 登录成功处理（根据新返回数据调整）
        if (result.code === 0) {  // 后端返回code=0表示成功找到用户并验证通过
            showToast('登录成功');  // 使用后端返回的msg提示
            // 保存用户信息（根据后端返回的data字段调整）
            localStorage.setItem('userInfo', JSON.stringify({
                uid: result.data.uid,
                email: result.data.email,
                // 注意：密码（pwd）不建议前端存储，根据业务需求决定是否保留
            }));
            localStorage.setItem('token', "假token");
            // 若后端返回token字段（当前示例未提供），则修改为 localStorage.setItem('token', result.data.token);
            router.push({ name: "Home" });
        } else {
            showToast('登录失败，请检查账号密码是否正确');
        }
    } catch (error) {
        showToast('网络请求失败，请检查接口或网络');
        console.error('登录错误:', error);
    }
};

const goRegister = () => {
    router.push({ name: "Register" });
}
</script>

<style scoped>
.login-container {
    padding: 20px;
    height: 80vh;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.top {
    padding: 200rpx 0 30rpx;
    display: flex;
    justify-content: center;
}

.logo {
    width: 100px;
    height: 100px;
    margin: 50px;
}

.bottom {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.register {
    color: #999;
    font-size: 24rpx;
}

.protocol {
    color: var(--van-primary-color);
    font-size: 24rpx;
}

.van-button {
    margin-top: 20px;
}
</style>